package com.wms.service.impl;

import com.wms.dto.SaveActualQtyCountDTO;
import com.wms.mapper.SaveTaskDetailActualQtyMapper;
import com.wms.mapper.StockTakingTaskMapper;
import com.wms.service.SaveTaskDetailActualQtyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class SaveTaskDetailActualQtyServiceImpl implements SaveTaskDetailActualQtyService {
    @Autowired
    SaveTaskDetailActualQtyMapper saveTaskDetailActualQtyMapper;

    @Autowired
    StockTakingTaskMapper stockTakingTaskMapper;

    @Override
    public int SaveTaskDetailActualQty(SaveActualQtyCountDTO saveActualQtyCountDTO) {
        try {
            //验证参数
            if (saveActualQtyCountDTO.getSaveActualQtyDTOList() == null || saveActualQtyCountDTO.getSaveActualQtyDTOList().isEmpty()) {
                throw new RuntimeException("盘点明细不能为空");
            }
            //根据任务编码查询任务id
            int taskId = saveTaskDetailActualQtyMapper.queryTaskDetailById(saveActualQtyCountDTO.getTaskCode());
            if (taskId < 0) {
                throw new RuntimeException("任务编码不存在");
            }
            //批量保存实际盘点数量
            int updateResult = saveTaskDetailActualQtyMapper.SaveTaskDetailActualQty(saveActualQtyCountDTO.getSaveActualQtyDTOList());
            if (updateResult < 0) {
                throw new RuntimeException("保存实际盘点数量失败");
            }
            //批量保存差异数量
            int updateDiffQty = saveTaskDetailActualQtyMapper.saveTaskDetailDiffQty(saveActualQtyCountDTO.getSaveActualQtyDTOList());
            if (updateDiffQty <=0) {
                throw new RuntimeException("保存差异数量失败");
            }
            //修改是否有破损的状态
            int updateBreakAge = saveTaskDetailActualQtyMapper.updateTaskDetailBreakage(saveActualQtyCountDTO.getSaveActualQtyDTOList());
            if (updateBreakAge <=0) {
                throw new RuntimeException("修改是否有破损的状态失败");
            }

            //检查任务完成情况
            int completedCount = saveTaskDetailActualQtyMapper.queryCompletedDetailCount(taskId);
            int totalCount = saveTaskDetailActualQtyMapper.queryTotalDetailCount(taskId);
            
            // 验证：检查传入的明细是否都有实际数量且大于0
            boolean allValid = saveActualQtyCountDTO.getSaveActualQtyDTOList().stream()
                    .allMatch(dto -> dto.getActualQty() != null && dto.getActualQty() > 0);
            
            // 调试信息：打印验证的关键数据
            System.out.println("=== 调试信息 ===");
            System.out.println("taskId: " + taskId);
            System.out.println("completedCount: " + completedCount);
            System.out.println("totalCount: " + totalCount);
            System.out.println("allValid: " + allValid);
            System.out.println("明细数据:");
            saveActualQtyCountDTO.getSaveActualQtyDTOList().forEach(dto -> 
                System.out.println("  ID: " + dto.getId() + ", actualQty: " + dto.getActualQty())
            );
            System.out.println("================");
            
            //根据完成情况自动调整完成状态
            if (completedCount == totalCount && totalCount > 0 && allValid) {
                // 只有当所有明细都有实际数量且大于0时，才设置为已完成
                System.out.println("设置为状态3（已完成）");
                saveTaskDetailActualQtyMapper.updateTaskStatus(taskId, 3);
                int updateAuditStatus = stockTakingTaskMapper.updateTaskAuditStatus(saveActualQtyCountDTO.getTaskCode());
                if (updateAuditStatus <= 0) {
                    throw new RuntimeException("修改审核状态失败");
                }
            } else if (completedCount > 0) {
                // 部分明细有实际数量，设置为部分完成
                System.out.println("设置为状态2（部分完成）");
                saveTaskDetailActualQtyMapper.updateTaskStatus(taskId, 2);
            } else {
                System.out.println("保持当前状态");
            }
            return updateResult;
        }catch (Exception e){
            throw new RuntimeException("批量保存失败"+e.getMessage());
        }
    }
}
